<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>实时文档</title>
    <!--适配手机-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <!--使用bootstrap的样式，比较好看-->
    <link href="http://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
    <!--jQuery-->
    <script
            src="http://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous"></script>
    <script src="https://cdn.bootcss.com/markdown.js/0.5.0/markdown.min.js"></script>
    <style>
        h1 {
            font-family: Consolas, monaco, monospace;
            font-size: 23px;
            font-style: normal;
            font-variant: normal;
            font-weight: 500;
            line-height: 23px;
            text-align: center;
        }

        h3 {
            font-family: Consolas, monaco, monospace;
            font-size: 17px;
            font-style: normal;
            font-variant: normal;
            font-weight: 500;
            line-height: 23px;
        }

        p {
            font-family: Consolas, monaco, monospace;
            font-size: 14px;
            font-style: normal;
            font-variant: normal;
            font-weight: 400;
            line-height: 23px;
        }

        blockquote {
            font-family: Consolas, monaco, monospace;
            font-size: 17px;
            font-style: normal;
            font-variant: normal;
            font-weight: 400;
            line-height: 23px;
        }

        pre {
            font-family: Consolas, monaco, monospace;
            font-size: 12px;
            font-style: normal;
            font-variant: normal;
            font-weight: 400;
            line-height: 23px;
        }

        #text-input {
            margin-left: 4%;
            padding: 15px;
            height: calc(100vh - 100px);
            width: 96%;
            border: none;
            resize: none;
        }

        #preview {
            padding: 15px;
            width: 96%;
            border: none;
            /*自动计算高度,100vh代表窗口高度,vw为宽度*/
            height: calc(100vh - 100px);
            overflow-y: auto;
            overflow-x: auto;
        }

        body {
            overflow-x: hidden;
        }
    </style>
</head>

<body>

<h1>实时文档</h1>
<div class="row" style="text-align: center">
    <input id="username" placeholder="昵称"/>
    <select id="fileSelect" onchange="selectChanged(this.options[this.options.selectedIndex].value)" name="选择文件">
    </select>
    <!--<h5 style="float: right;margin-right: 200px">当前用户数量</h5>-->
    <button id="btn_login" onclick="login()">连接</button>
    <button onclick="disConn()">断开连接</button>


    <input id="newFileName" style="margin-left: 100px" placeholder="文件名"/>
    <button onclick="createFile()">新建文件</button>
</div>


<div style="margin-top: 10px" class="row">
    <div class="col-md-6">
        <textarea class="bg-success" id="text-input" oninput="this.editor.update()" rows="6"></textarea>
    </div>
    <div class="col-md-6">
        <div id="preview" class="bg-primary" rows="6"></div>
    </div>
</div>


<script>
    //登录状态
    var logined = false;
    <!--websocket实例-->
    var ws;

    //新建文件
    function createFile() {
        var newFileName = getEById("newFileName").value
        if (newFileName == '') {
            alert("文件名不能为空")
            return;
        }
        console.log(newFileName)

        $.ajax(
            {
                url: `http://${window.location.host}/create/file`,
                type: 'post',
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify({
                    newFileName: newFileName
                }),
                success: function (res) {
                    console.log('res', res)
                    alert(res.msg)
                    if (res.code == 1) {
                        getFileSelect()
                    }
                },
                error: function (res) {
                    console.error(res)
                }
            }
        )
    }

    getFileSelect()


    // //创建定时任务(10秒渲染一次下拉框)
    // setInterval(function () {
    //     console.log("渲染文件选择框");
    //     getFileSelect()
    // }, 10000);

    //渲染文件下拉框
    function getFileSelect() {
        $.ajax(
            {
                url: `http://${window.location.host}/list/file`,
                type: 'GET',
                success: function (res) {
                    console.log("成功", res)
                    //渲染列表
                    $("#fileSelect").empty()
                    $("#fileSelect").append(`<option value="0">
                        请选择文件
                        </option>`)
                    if (res) {
                        if (res.code == 1) {
                            if (res.data.length > 0) {
                                for (var i = 0; i < res.data.length; i++) {
                                    $("#fileSelect").append(`<option value=${res.data[i]}>${res.data[i]}</option>`)
                                }
                            }
                        }
                    }

                },
                error: function (res) {
                    console.error("请求失败", res)
                }
            }
        )
    }

    //断开连接
    function disConn() {
        try {
            ws.close()
        } catch (e) {
            // alert("请先登录")
        }
        getEById("btn_login").disabled = false;
        $("#btn_login").html('连接')
        logined = false;
    }

    function login() {
        //获取昵称
        var username = getEById("username").value;

        var fileName = getEById("fileSelect").value;

        console.log(fileName)

        if (username == '') {
            alert("请输入昵称")
            return;
        } else if (fileName == 0) {
            alert("请选择文件")
            return;
        }

        console.log(username)
        //websocket
        ws = new WebSocket(`ws://${window.location.host}/websocket/${username}/${fileName}`);
        console.log('aaaaaaaa')

        ws.onopen = function () {
            // Web Socket 已连接上，使用 send() 方法发送数据
            // ws.send("已连接");
            // alert("数据发送中...");
        };

        ws.onclose = function () {
            // 关闭 websocket
            console.log("连接已关闭...");
        };

        ws.onmessage = function (evt) {
            var received_msg = evt.data;
            getEById("text-input").value = received_msg;
            getEById("preview").innerHTML = markdown.toHTML(received_msg);

            //alert(received_msg);
        };

        getEById("btn_login").disabled = true;
        $("#btn_login").html('已连接')
        logined = true;
    }

    function selectChanged(value) {
        console.log("当前选中的文件", value)
        console.log('aaa', getEById("fileSelect").value)
        disConn()
        login()
    }


    //编辑器实例(输入内容组件,预览内容组件)
    function Editor(input, preview) {
        this.update = function () {
            //preview.innerHTML = markdown.toHTML(input.value);
            //console.log('aaa',input.value);
            try {
                ws.send(input.value)
            } catch (e) {
                alert("请先登录")
            }
        };
        input.editor = this;
    }

    //封装$为函数
    var getEById = function (id) {
        return document.getElementById(id);
    };
    //绑定DOM
    new Editor(getEById("text-input"), getEById("preview"));


</script>
</body>

</html>

